<script>
  import Card from "./Card.svelte";
  import Button from "./Button.svelte";
  import RatingSelect from "./RatingSelect.svelte";
  import {v4 as uuidv4} from "uuid";
  import {FeedbackStore} from "../stores";


  let text = "";
  let btnDisabled = true;
  let min = 10;
  let message;
  let rating = 10;


  const handleInput = () => {
    if (text.trim().length < min) {
      message = `Text must be at least ${min} characters`;
      btnDisabled = true;
    } else {
      message = null;
      btnDisabled = false;
    }
  };

  const handleSelect = e => rating = e.detail;

  const handleSubmit = () => {
    if (text.trim().length >= min) {
      const newFeedback = {
        id: uuidv4(),
        text,
        rating: +rating
      }
      FeedbackStore.update((currentFeedback) => {
        return [newFeedback, ...currentFeedback];
      });
      text = "";
    }
  };

</script>


<Card>
  <header class="w-80 mx-auto">
    <h2 class="text-xl font-bold text-center">
      How would you rate your service with us?
    </h2>
  </header>
  <form on:submit|preventDefault={handleSubmit}>
    <RatingSelect on:rating-select={handleSelect}/>
    <!--Rating Select-->
    <div class="input-group flex border border-gray-200 p-2 rounded-md mt-3">
      <input class="flex-1 focus:outline-none border-0  text-xs" type="text" bind:value={text} on:input={handleInput} placeholder="Tell us something that keeps you coming back">
      <Button type="submit" disabled={btnDisabled} >Send</Button>
    </div>
    {#if message}
      <div class="message mt-2 text-center text-purple-700">
        {message}
      </div>
    {/if}
  </form>
</Card>


